var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/school';
var async = require('async');


router.post('/',function(req,res){
	//var email = req.session.email || '';
	var username = req.session.username || '';
	if (username) {
	//设置日期格式
	var time=new Date();
	time=time.getFullYear()+'-'+(time.getMonth()+1)+'-'+time.getDate()+' '+time.getHours()+':'+time.getMinutes()+':'+time.getSeconds();
	var movieName="电影名称";
	var comment=req.param('content');

	var pageNo = req.query.pageNo,
		pageNo = pageNo?pageNo:1,
		pageSize = 2,
		count = 0,
		totalPages = 0;
	var queryData = function(db,callback){
		//连接表
		var conn = db.collection('comment');
		//并行无关联
		async.parallel([
			function(callback){
				conn.find({}).toArray(function(err,results){
					if(err){
						return;
					}else{
						totalPages = Math.ceil(results.length/pageSize);
						count = results.length;

						// 第一个数组内容，我们返回的是空，并没有将count/totalPages当成回调返回，原因是什么呢？
						// 因为我们已经把total/totalPages设置成了js的全局变量，我在下面可以单独的去启用它们
						callback(null,'');
					}
				})
			},
			function(callback){
				conn.find({}).sort({_id:-1}).skip( (pageNo-1)*pageSize ).limit(pageSize).toArray(function(err,results){
					if(err){
						return;
					}
					callback(null,results);
				});
			}
		],function(err,results){
			callback(results[1]);
		})
	}

	//声明向数据库插入评论的方法insertCommend
	var insertCommend=function(db,callback){
		var conn=db.collection('comment');
		// var data1
		var data=[{movieName:movieName,username:username,comment:comment,time:time}];
		conn.insert(data,function(error,results){
			if(error){
				console.log(error)
				return;
			}
			console.log(data);
			callback(results);

		});
		//conn.find({}).sort({time:-1}).toArray(function(error,results){
			
					// data1.pageNo = pageNo;
					// data1.totalPages = totalPages;
					// data1.count = count;
					// data1.comments = comments;
					// data1.user = 1
					// console.log("12312132132")
					
	//});
}

		// req.session.time=time;
		/*res.render('list',{})*/
		MongoClient.connect(DB_CONN_STR,function(error,db){
			if(error){
				return;
			}else{
				// 调用上面的insertCommen方法将评论插入数据库
				insertCommend(db,function(results){
					console.log('评论成功!!!!!!'+time);
					//db.close();
				})
				queryData(db,function(results){
					var data = {
						pageNo:pageNo,
						totalPages:totalPages,
						comments:results,
						count:count
					}
					console.log(data);
					res.render('detail', data);
				});
			}

		})

	}else{
		res.send("<script>alert('请登录！');location.href='/login';</script>")
	}
	
	
});


module.exports = router;